#include "daemon_runner.h"
typedef struct
{
    char *path;
    char *args;
    int pid;
} sub_process_t;

gate_status_t daemon_runner_check_process(sub_process_t *process)
{
    if (process->pid > 0) // 进程曾经启动过
    {
        pid_t pid = waitpid(process->pid, NULL, WNOHANG);
        if (pid == 0)
        {
            log_info("process %s(%d) is running", process->path, process->pid);
            return GATE_OK;
        }
        else if (pid > 0)
        {
            log_info("process %s(%d) is dead", process->path, process->pid);
        }
        else if (pid < 0)
        {
            log_error("process %s(%d) is error", process->path, process->pid);
        }
    }

    process->pid = -1;
    // 启动进程
    pid_t pid = fork();
    if (pid == 0)
    {
        // 启动进程
        log_info("process %s %s is error", process->path, process->args);
        execl(process->path, process->path, process->args, NULL);

        perror("execl启动失败");
        return GATE_ERROR;
    }
    else if (pid > 0)
    {
        process->pid = pid;
    }
    else
    {
        log_error("fock process %s(%d) is error", process->path, process->pid);
        return GATE_ERROR;
    }

    return GATE_OK;
}

void daemon_runner_run(void)
{
    // 把该进程设置为后台进程
    // 参数1: 是否切换到根目录 参数2: 是否关闭便准输入输出错误输出
    daemon(0, 1);

    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    open("/dev/null", O_RDWR);                                    // 输入重定向
    open("/root/gateway.log", O_RDWR | O_CREAT | O_APPEND, 0666); // 输出重定向
    open("/root/gateway.log", O_RDWR | O_CREAT | O_APPEND, 0666); // 错误重定向重定向

    // 检测 其他进程(app ota)是否还在运行, 如果没有运行,则启动,如果在运行,就不管

    sub_process_t app = {
        .path = "/usr/bin/gateway",
        .args = "app",
        .pid = -1};

    sub_process_t ota = {
        .path = "/usr/bin/gateway",
        .args = "ota",
        .pid = -1};

    while (1)
    {
        daemon_runner_check_process(&app);
        daemon_runner_check_process(&ota);
        sleep(2);
    }
}
